package com.lanchetech.admin.service.impl;

import com.alibaba.excel.util.CollectionUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanchetech.admin.service.RoomService;
import com.lanchetech.bean.request.AnchorReq;
import com.lanchetech.bean.request.RoomReq;
import com.lanchetech.bean.response.BasePageResp;
import com.lanchetech.bean.response.BaseResp;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.bean.util.PageHelpUtil;
import com.lanchetech.bean.vo.AnchorVO;
import com.lanchetech.bean.vo.RoomVO;
import com.lanchetech.common.enums.DeletedEnum;
import com.lanchetech.dao.IdentityMapper;
import com.lanchetech.dao.RoomMapper;
import com.lanchetech.dao.RoomSpuMapper;
import com.lanchetech.entity.Room;
import com.lanchetech.entity.User;
import com.lanchetech.service.DaoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RoomServiceImpl implements RoomService {

    @Autowired
    RoomMapper roomMapper;

    @Autowired
    IdentityMapper identityMapper;

    @Autowired
    DaoService daoService;

    @Autowired
    RoomSpuMapper roomSpuMapper;

    @Override
    public ResultData<BasePageResp<RoomVO>> getRoomPage(RoomReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<Room> list = roomMapper.findAllPage(req);
        List<RoomVO> voList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(list)){
            Map<Long,User> userMap = daoService.getUserMap(list.stream().map(Room::getAnchorUserId).collect(Collectors.toList()));
            list.stream().forEach(item->{
                RoomVO vo= new RoomVO();
                BeanUtils.copyProperties(item,vo);
                vo.setUserAvatar(userMap.get(item.getAnchorUserId()).getAvatar());
                vo.setUserNickname(userMap.get(item.getAnchorUserId()).getNickname());
                voList.add(vo);
            });
        }
        return PageHelpUtil.buildPage(voList, page);
    }

    @Override
    public BaseResp deleteRoom(Long id) {
        roomMapper.updateDeletedById(DeletedEnum.DELETED.getStatus(), id);

        roomSpuMapper.deleteByRoomId(id);
        return new BaseResp();
    }

    @Override
    public BaseResp editRoomStatus(Long id, Byte status) {
        roomMapper.updateStatusById(status,id);
        return new BaseResp();
    }

    @Override
    public BaseResp editRoomSort(Room req) {
        roomMapper.updateSortsById(req.getSorts(), req.getId());
        return new BaseResp();
    }
}
